<template>
  <van-cell :title="label">
    <template #label>
      <div class="number-select-content">
        <van-popover
          v-model:show="showPopover"
          :actions="actions"
          style="flex: 0 0 auto"
          placement="bottom-start"
          @select="onSelect"
        >
          <template #reference>
            <van-button hairline size="small">{{ currentAction }}</van-button>
          </template>
        </van-popover>
        <van-field
          v-if="isSingleInput"
          v-model="numberData[0]"
          placeholder="请输入数值"
          type="number"
          @blur="saveInputValue"
        />
        <template v-else>
          <van-field v-model="numberData[0]" placeholder="请输入最小值" type="number" @blur="saveInputValue" />
          <van-field v-model="numberData[1]" placeholder="请输入最大值" type="number" @blur="saveInputValue" />
        </template>
      </div>
    </template>
  </van-cell>
</template>

<script setup lang="ts">
import { FIELD_TYPE } from '@/framework/types/portal'
import { showError, showWarning } from '@/framework/common/notify'
import { getRelation } from '@/framework/components/PortalData/DataFilter/funs'
import { NumberStringArray } from '@/framework/types/common-data'

const props = defineProps<{
  fieldType: FIELD_TYPE
  value: NumberStringArray
  label: string
}>()

const { fieldType, label } = toRefs(props)

const actions = ref([])
let showPopover = ref(false)
let isSingleInput = ref(true)
let currentAction = ref('选择关系')
// 前两位是数字，最后一位是标志位，标记是一个输入框还是两个
let numberData: Ref<NumberStringArray> = ref(['', ''])
const multipleInputNameSet = new Set(['介于', '之间'])

const emit = defineEmits<{
  (e: 'update:value', value: NumberStringArray): void
}>()

const onSelect = (action: any) => setCurrentAction(action.text)

onBeforeMount(() => {
  getRelation(fieldType.value).then((data) => {
    actions.value = data
    if (!data.length) {
      showError('后台接口数据有误，请联系管理员')
      return
    }
    setCurrentAction(data[0].text)
  })
})

const setCurrentAction = (text: string) => {
  currentAction.value = text
  numberData.value = ['', '']
  isSingleInput.value = !multipleInputNameSet.has(text)
}

watch(
  () => props.value,
  (value) => (numberData.value = value)
)

// 在这里拦截异常没用，因为用户可能输入完信息后直接点击提交
const saveInputValue = () => {
  if (!isSingleInput.value) {
    if (!numberData.value[0] || !numberData.value[1])
      showWarning(`请确保 ${label.value} 属性同时输入了最小值和最大值`)
    emit('update:value', numberData.value)
  } else emit('update:value', [numberData.value[0]])
}
</script>

<style scoped>
.number-select-content {
  display: flex;
  align-items: center;
}
:deep(.number-select-content .van-popover__wrapper) {
  flex: 0 0 auto;
}
</style>
